package com.yyfax.demo.watch;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;

public class FileCopy {
	public static void main(String[] args) throws IOException {

		File s = new File("C:\\Users\\thinkpad\\git\\demo");
		File t = new File("d:\\demo");
		copyFolder(s, t);
	}

	/**
	 * 复制一个目录及其子目录、文件到另外一个目录
	 * 
	 * @param src
	 * @param dest
	 * @throws IOException
	 */
	static void copyFolder(File src, File dest) throws IOException {
		if (src.isDirectory()) {
			if (!dest.exists()) {
				dest.mkdir();
			}
			String files[] = src.list();
			for (String file : files) {
				File srcFile = new File(src, file);
				File destFile = new File(dest, file);
				// 递归复制
				copyFolder(srcFile, destFile);
			}
		} else {
			InputStream in = new FileInputStream(src);
			
			String destFilename = getExtensionName(dest.getName());
			
			System.out.println(" destFilename =  " + destFilename);
			
			
			System.out.println(" dest.getAbsolutePath() =  " + dest.getAbsolutePath());
			
			
			
			
			
			OutputStream out = null;
			
			if("java".equals(destFilename)) {

				File  newDest = new File(dest.getAbsolutePath() + ".new");
				
				out = new FileOutputStream(newDest);
			} else {
				
				out = new FileOutputStream(dest);
			} 
			

			byte[] buffer = new byte[1024];

			int length;

			while ((length = in.read(buffer)) > 0) {
				out.write(buffer, 0, length);
			}
			in.close();
			out.close();
		}
	}
	
	
	 public static String getExtensionName(String filename) {   
	        if ((filename != null) && (filename.length() > 0)) {   
	            int dot = filename.lastIndexOf('.');   
	            if ((dot >-1) && (dot < (filename.length() - 1))) {   
	                return filename.substring(dot + 1);   
	            }   
	        }   
	        return filename;   
	    }  
}
